<template>
  <div class="approval-select-container">
    <!-- 顶部标题栏 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">发起审批</h2>
        <span class="process-count">{{ enabledProcessCount }} 个可用流程</span>
      </div>
      <div class="header-right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索流程名称"
          prefix-icon="el-icon-search"
          size="small"
          style="width: 260px;"
          clearable
        />
      </div>
    </div>

    <!-- 分类卡片视图 -->
    <div class="category-view">
      <div 
        v-for="category in categories" 
        v-if="getCategoryEnabledProcesses(category.value).length > 0"
        :key="category.value"
        class="category-section"
      >
        <template >
          <div class="category-header">
            <div class="category-title">
              <i :class="category.icon" :style="{ color: category.color }"></i>
              <span class="category-name">{{ category.label }}</span>
              <el-badge 
                :value="getCategoryEnabledProcesses(category.value).length" 
                class="category-badge" 
              />
            </div>
            <span class="category-description">{{ category.description }}</span>
          </div>

          <div class="process-cards">
            <div 
              v-for="process in getCategoryEnabledProcesses(category.value)" 
              :key="process.id"
              class="process-card"
              @click="startApproval(process)"
            >
              <div class="card-icon">
                <i :class="process.icon || 'el-icon-document'"></i>
              </div>
              <div class="card-content">
                <h3 class="process-name">{{ process.processName }}</h3>
                <p class="process-description">
                  {{ process.description || '点击发起审批申请' }}
                </p>
              </div>
              <div class="card-arrow">
                <i class="el-icon-arrow-right"></i>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- 全局空状态 -->
    <div v-if="enabledProcessCount === 0 && !searchKeyword" class="global-empty">
      <i class="el-icon-document-delete"></i>
      <p class="empty-title">暂无可用的审批流程</p>
      <p class="empty-description">请联系管理员创建审批流程</p>
    </div>

    <!-- 搜索无结果 -->
    <div v-if="enabledProcessCount === 0 && searchKeyword" class="global-empty">
      <i class="el-icon-search"></i>
      <p class="empty-title">未找到相关流程</p>
      <p class="empty-description">试试其他关键词</p>
      <el-button type="text" @click="searchKeyword = ''">清空搜索</el-button>
    </div>

    <!-- 最近使用 -->
    <div v-if="recentProcesses.length > 0" class="recent-section">
      <div class="section-header">
        <i class="el-icon-time"></i>
        <span>最近使用</span>
      </div>
      <div class="recent-list">
        <div
          v-for="process in recentProcesses"
          :key="'recent-' + process.id"
          class="recent-item"
          @click="startApproval(process)"
        >
          <i :class="process.icon || 'el-icon-document'" class="recent-icon"></i>
          <span class="recent-name">{{ process.processName }}</span>
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getStartableProcesses } from '@/api/process'

export default {
  name: 'ApprovalSelect',
  
  data() {
    return {
      processList: [],
      searchKeyword: '',
      recentProcessIds: [],
      
      // 审批分类配置（与 ProcessList 保持一致）
      categories: [
        {
          value: 'leave',
          label: '请假申请',
          icon: 'el-icon-s-check',
          color: '#409EFF',
          description: '员工请假审批'
        },
        {
          value: 'reimbursement',
          label: '报销申请',
          icon: 'el-icon-money',
          color: '#67C23A',
          description: '费用报销审批'
        },
        {
          value: 'purchase',
          label: '采购申请',
          icon: 'el-icon-shopping-cart-2',
          color: '#E6A23C',
          description: '物资采购审批'
        },
        {
          value: 'other',
          label: '其他流程',
          icon: 'el-icon-document',
          color: '#909399',
          description: '其他审批流程'
        }
      ]
    }
  },
  
  computed: {
    // 只显示启用的且有权限发起的流程
    enabledProcessList() {
      let list = this.processList.filter(p => p.status === 1 && p.canStart)
      
      // 搜索过滤
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase()
        list = list.filter(p => 
          p.processName.toLowerCase().includes(keyword) ||
          (p.description && p.description.toLowerCase().includes(keyword))
        )
      }
      
      return list
    },
    
    // 启用流程数量
    enabledProcessCount() {
      return this.enabledProcessList.length
    },
    
    // 最近使用的流程
    recentProcesses() {
      if (this.recentProcessIds.length === 0) return []
      
      return this.recentProcessIds
        .map(id => this.enabledProcessList.find(p => p.id === id))
        .filter(p => p !== undefined)
        .slice(0, 5) // 最多显示5个
    }
  },
  
  created() {
    this.loadProcessList()
    this.loadRecentProcesses()
  },
  
  methods: {
    loadProcessList() {
      getStartableProcesses()
        .then(res => {
          console.log(res)
          if (res.code === 200) {
            this.processList = res.data || []
            // 使用权限过滤后的API，不需要再检查权限
          } else {
            this.$message.error('加载流程列表失败')
          }
        })
        .catch(error => {
          console.error('加载流程列表失败:', error)
          this.$message.error('加载流程列表失败')
        })
    },
    
    // 加载最近使用的流程
    loadRecentProcesses() {
      const recent = localStorage.getItem('recentApprovalProcesses')
      if (recent) {
        try {
          this.recentProcessIds = JSON.parse(recent)
        } catch (e) {
          this.recentProcessIds = []
        }
      }
    },
    
    // 保存最近使用的流程
    saveRecentProcess(processId) {
      // 移除已存在的
      this.recentProcessIds = this.recentProcessIds.filter(id => id !== processId)
      // 添加到开头
      this.recentProcessIds.unshift(processId)
      // 最多保存10个
      this.recentProcessIds = this.recentProcessIds.slice(0, 10)
      // 保存到本地存储
      localStorage.setItem('recentApprovalProcesses', JSON.stringify(this.recentProcessIds))
    },
    
    // 获取指定分类的启用流程
    getCategoryEnabledProcesses(category) {
      return this.enabledProcessList.filter(p => p.category === category)
    },
    
    // 发起审批
    startApproval(process) {
      // 再次检查权限（双重保险）
      if (!process.canStart) {
        this.$message.error(process.permissionMessage || '您没有权限发起此流程')
        return
      }
      
      // 保存到最近使用
      this.saveRecentProcess(process.id)
      
      // 跳转到发起审批页面
      this.$router.push({
        path: `/approval/start/${process.id}`,
        query: {
          name: process.processName
        }
      })
    }
  }
}
</script>

<style scoped>
.approval-select-container {
  background: #f5f7fa;
  padding: 20px;
  min-height: calc(100vh - 100px);
}

/* 顶部标题栏 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.process-count {
  padding: 4px 12px;
  background: #f0f2f5;
  border-radius: 12px;
  font-size: 13px;
  color: #606266;
}

/* 分类视图 */
.category-view {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.category-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f2f5;
}

.category-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.category-title i {
  font-size: 24px;
}

.category-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.category-badge {
  margin-left: 8px;
}

.category-description {
  font-size: 13px;
  color: #909399;
}

/* 流程卡片 */
.process-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.process-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.process-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  transform: translateY(-2px);
}

.card-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}

.card-icon i {
  font-size: 24px;
  color: #fff;
}

.card-content {
  flex: 1;
  min-width: 0;
}

.process-name {
  margin: 0 0 6px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.process-description {
  margin: 0;
  font-size: 13px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-arrow {
  flex-shrink: 0;
  color: #c0c4cc;
  font-size: 18px;
  transition: all 0.3s;
}

.process-card:hover .card-arrow {
  color: #409eff;
  transform: translateX(4px);
}

/* 最近使用 */
.recent-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-top: 24px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.section-header i {
  font-size: 20px;
  color: #909399;
}

.recent-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.recent-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: #f5f7fa;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.recent-item:hover {
  background: #ecf5ff;
  color: #409eff;
}

.recent-icon {
  font-size: 18px;
  color: #909399;
}

.recent-item:hover .recent-icon {
  color: #409eff;
}

.recent-name {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
}

.recent-item i:last-child {
  font-size: 14px;
  color: #c0c4cc;
  transition: all 0.3s;
}

.recent-item:hover i:last-child {
  color: #409eff;
  transform: translateX(4px);
}

/* 空状态 */
.global-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.global-empty i {
  font-size: 80px;
  color: #c0c4cc;
  margin-bottom: 20px;
}

.empty-title {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #606266;
}

.empty-description {
  margin: 0 0 24px 0;
  font-size: 14px;
  color: #909399;
}

/* 响应式 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-left {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-right {
    width: 100%;
  }
  
  .header-right .el-input {
    width: 100% !important;
  }
  
  .process-cards {
    grid-template-columns: 1fr;
  }
}
</style>

